<?php

namespace App\Http\Controllers;

use App\Comment;
use App\Discuss;
use App\Http\Requests;
use App\Parsedown;
use App\Review;
use App\Study;
use App\Studyfav;
use App\Task;
use App\Solve;
use App\User;
use App\Utils;
use Auth;
use Cache;
use Cookie;
use DB;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Input;
use Log;
use Mail;
use Redirect;
use Reponse;
use View;
use Crypt;
use DateTime;


class testController extends Controller
{
    public function __construct()
    {
        //          $this->middleware('auth');
    }
	public function m2h(Request $request)
	{
	}
	public function spider5(Request $request)
	{
		 if ($request->isMethod('post'))
		 {
			 $input=$request->all();
			 $arr=array();
			 $t1=time();
			 $t2=time();
			 foreach($input as $k=>$v)
			 {
				 if($k=="_token")continue;
				 $str=Crypt::decrypt($k);
				 $t1=substr($str,1);
				 if($t2-$t1>20)
				 {
					 echo "请在20秒内完成注册";
					 return;
				 }
				 $kk=substr($str,0,1);
				 $arr[$kk]=$v;
			 }

				 $u=User::whereName($arr["7"])->get();
			 if(count($u)==0)
			 {
				 echo "推荐人不存在";
				 return;
			 }
			 //username
			 $error=0;
			 if(strlen($arr["0"])<3||strlen($arr["0"])>10)
			 {
				 echo "用户名的长度范围在3-7的全英文";
				 $error=1;
			 }
			 //password
			 else if(strlen($arr["1"])<20)
			 {
				 echo "密码少于20位是不安全的";
				 $error=1;
			 }
			 else if(strlen($arr["2"])!=11)
			 {
				 echo "天朝的手机号码是11位的";
				 $error=1;
			 }
			 else if(strpos($arr["3"],"@")==-1)
			 {
				 echo "邮箱格式不对";
				 $error=1;
			 }
			 else if(strlen($arr["4"])!=1)
			 {
				 echo "性别填0 or 1，0代表0，1代表1";
				 $error=1;
			 }
			 else if(strlen($arr["5"])!=8)
			 {
				echo "生日是一个8位字符串，举例:19850105";
				 $error=1;
			 }
			 else if($arr["6"]!=$arr["1"])
			 {
				 echo "两次密码输入不一致";
				 $error=1;
			 }
			 $uid=$u->first()->id;
			 $solves=Solve::whereUseridAndTaskid($uid,122)->get();
			 if(count($solves)>0)
			 {
				 $solve=$solves->first();
				 if($error==0)
				 $solve->score+=1;
				 else $solve->score-=1;
				 if($solve->score<0)$solve->score=0;
				 if($solve->rscore==$t1)
				 {
					 echo "发现重复的表单提交,请刷新页面重新注册";
					 return;
				 }
				 $solve->rscore=$t1;
				 if($error==0)
				 echo "恭喜你，注册成功，你的推荐人已经推荐了".$solve->score."个基佬加入了千里基";
				 else
				 echo "<br>woo~你又注册失败了，系统怀疑你是一个低端的自动注册机器人，因此把你的推荐人的推荐数减1了，目前你的推荐人已经推荐了".$solve->score."个基佬加入了千里基";
				 if($solve->score>=1000)
				 {
					 $solve->type=0;
					 $solve->rscore=0;
					 echo "<br>恭喜你通过此题";
				 }
				 $solve->save();
			 }
			 else if($error==0)
			 {
				 $data=array();
				 $data['userid']=$uid;
				 $data['taskid']=122;
				 $data['type']=1;
				 $data['score']=1;
				 Solve::create($data);
				 echo "恭喜你，注册成功，你的推荐人已经推荐了1个基佬加入了千里基";

			 }

			 return;
		 }
		//$str=Crypt::encrypt("123");
		//var_dump(Crypt::decrypt($str));
		$magicpos=10;
		$arr=array();
		for($i=0;$i<8;$i++)
		{
			$p=time();
			$arr[]=Crypt::encrypt($i.$p);
		}
		shuffle($arr);
		return View::make("train.spider5")->with(compact('arr'));
	}
	public function index(Request $request,$p)
	{
		$p=substr(Crypt::decrypt($p),0,1);
if($p%8==0)$text="username";
else if($p%8==1)$text = "password";
else if($p%8==2)$text = "phone";
else if($p%8==3)$text = "email";
else if($p%8==4)$text = "sex";
else if($p%8==5)$text = "birthday";
else if($p%8==6)$text = "re-password";
else if($p%8==7)$text = "introducer";
Header("Content-type: image/png");
$font ="/root/work/public/fonts/AnkeCalligraph.TTF";
mt_srand();
$width=150+mt_rand(0,10);
$height=30+mt_rand(0,4);
$im = imagecreate($width,$height);
$black = ImageColorAllocate($im, 0,0,0);
$white = ImageColorAllocate($im, mt_rand(150,255),mt_rand(150,255),mt_rand(150,255));
$pix= ImageColorAllocate($im,mt_rand(0,150),mt_rand(0,150),mt_rand(0,150));
for($i=0;$i<100;$i++)
{
	imagesetpixel($im,$width,$height,$pix);
}
imagettftext($im,mt_rand(14,20), mt_rand(0,6)-3, 10, 20, $white, $font, $text);
imagepng($im);
ImageDestroy($im);
	}

    public function index2(Request $request)
    {
        for ($i = 142; $i <= 142; $i++) {
            $taskid = $i;
            $task = Task::find($taskid);
            $data = array();
            $data['tag'] = $task->title;
            $data['title'] = $task->title . "的学习资料";
            $data['content'] = "关于" . $task->title . "的学习资料的汇总";
            $data['userid'] = 55;
            $data['rtime'] = time();
            $d = Discuss::create($data);
            $id = $d->id;
            $studies = Study::whereTaskidAndDelete($taskid, 0)->get();
            foreach ($studies as $s) {
                $data = array();
                $data['taskid'] = $id;
                $data['type'] = 1;
                $data['userid'] = $s->userid;
                $data['comment'] = $s->content;
                $data['vote'] = $s->vote;
                $data['created_at'] = $s->created_at;
                $data['updated_at'] = $s->updated_at;
                Comment::create($data);
            }
        }

    }
	public function person(Request $request)
	{
		return View::make("person.detail");
	}

	public function questions(Request $request, $tag = "all", $type = "new")
    {
		Utils::log($request, 'questions');
        $order = "rtime";
        if ($type == 'hot') $order = "ansnum";
        if ($type == 'unanswered') $order = "created_at";
        $permission = 0;
        if (Auth::check()) {
            $permission = Auth::user()->permission;
        }
        if ($type == "unanswered") {
            if ($tag == "all")
                $questions = Discuss::whereDeleteAndAnsnum(0, 0)->where('permission', '<=', $permission)->orderby("type", "asc")->orderby($order, "desc")->paginate(20);
            else {
				if (Auth::check() && Auth::user()->score >= 100 * 30)
				{
					$questions = Discuss::whereDeleteAndAnsnumAndTag(0, 0, $tag)
						->where('permission', '<=', $permission)
						->where('id', '!=', '284')
						->where('id', '!=', '291')
						->orderby($order, "desc")->paginate(20);
				}
				else
				{
					$questions = Discuss::whereDeleteAndAnsnumAndTag(0, 0, $tag)->where('permission', '<=', $permission)->orderby($order, "desc")->paginate(20);
				}
			}
        } else {
            if ($tag == "all")
                $questions = Discuss::whereDelete(0)->orderby("type", "asc")->where('permission', '<=', $permission)->orderby($order, "desc")->paginate(20);
            else
				if (Auth::check() && Auth::user()->score >= 100 * 30)
					$questions = Discuss::whereDeleteAndTag(0, $tag)
						->where('permission', '<=', $permission)
						->where('id', '!=', '284')
						->where('id', '!=', '291')
						->orderby($order, "desc")->paginate(20);
				else
                	$questions = Discuss::whereDeleteAndTag(0, $tag)->where('permission', '<=', $permission)->orderby($order, "desc")->paginate(20);
        }

        foreach ($questions as $q) {
            $q->user = User::find($q->userid);

            $comment = Comment::whereTypeAndTaskidAndDelete(1, $q->id, 0)->orderBy("created_at", "desc")->take(1)->get();
            if (count($comment) == 0) continue;
            $comment[0]->user = User::find($comment[0]->userid);
            $q->firstc = $comment[0];

        }
        if ($tag != "all" && $tag != 'topic') {
            $task = Task::whereTitle($tag)->get()->first();
            $task->user = User::find($task->contributor);
        }
        return View::make("dis.questions")->with(compact('type'))->with(compact('questions'))->with(compact('tag'))->with(compact('task'));
    }

    public function show(Request $request, $id, $id2 = 0)
    {
        $id = Utils::url2id($id);
        if ($id2 != "0") $id2 = Utils::url2id($id2);
        $dis = Discuss::findOrFail($id);
        $type = 'discuss';
        if ($dis->tag == 'topic') {
            $type = 'topic';
        }
		$permission = 0;
		if (Auth::check() && Auth::user()->permission > 0) {
			$permission = Auth::user()->permission;
		}
        if ($permission < $dis->permission) {
            return View::make('errors.404');
        }
        $tasks = Task::whereTitle($dis->tag)->get();
        $dis->vote += 1;

        $parser = new ParseDown();
		$comments = Comment::whereTypeAndTaskidAndDelete(1, $id, 0)->get();
		$comments = $comments->sortBy('created_at');
		$dis->ansnum = $comments->count();
		$dis->save();

        $dis->content = $parser->text($dis->content);
        $dis->user = User::find($dis->userid);


		$ended = true;
		if ($dis->end_time != null) {
			$now = new DateTime();
			$end = new DateTime($dis->end_time);
			if ($dis->tag == 'topic' && $now < $end) {
				$ended = false;
			}
		}
		$count = 1;
        foreach ($comments as $c) {
			$c->user = User::find($c->userid);
			if (!$ended) {
				$c->user->name = "第" . $count . "位回复者";
				$c->user->introduce = null;
			}
			$count += 1;
			//TODO:我想到了一种非常轻松的解决xss的方案，这里空白太小了，我写不下了。
		//	if($c->id==8061) $c->comment = $c->comment_html;
		//	else 
			$c->comment = $parser->text($c->comment);
            $c->votes = Studyfav::where('type', 1)->where('studyid', $c->id)->get();
            $respons = Comment::whereTypeAndTaskidAndDelete(3, $c->id, 0)->orderBy("created_at", "asc")->get();
			$c->commented = 0;
			foreach ($respons as $r) {
                $r->user = User::find($r->userid);
				if (!$ended && $r->userid == $c->userid) {
					$r->user->name = "(本回复作者)";
				}
                if ($r->ruserid != 0) {
					$r->ruser = User::find($r->ruserid);
					if (!$ended && $r->ruserid == $c->userid) {
						$r->ruser->name = "(本回复作者)";
					}
				}
				if (Auth::check() && $r->userid == Auth::user()->id && strlen($r->comment) >= 20) {
					$c->commented = 1;
				}
            }
            $c->respons = $respons;
            $c->fav = 0;
            if (Auth::check() && Auth::user()->id != $c->userid) {
                $fav = Studyfav::whereUseridAndStudyidAndType(Auth::user()->id, $c->id, 1)->orderBy('created_at', 'desc')->get()->first();
                if ($fav != null && $fav->vote_type == 0) {
					$c->fav = 1;
				}
				if ($fav != null && $fav->vote_type == 1) {
					$c->fav = 2;
				}
            }
        }
		$comments = $comments->sortByDesc('score');
		return View::make("dis.p")->with(compact("dis"))->with(compact("comments"))->with(compact("tasks"))->with(compact('type'))->with(compact('ended'));
    }
	public function testreact(Request $request)
	{
		return View::make("react.index");
	}
}
